package com.luoyuanxiangvip.common.config;

import com.luoyuanxiangvip.common.properties.ThreadPoolTaskProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 线程池配置
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/6/15
 */
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {

    @Resource
    private ThreadPoolTaskProperties threadPoolTaskProperties;

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolTaskProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolTaskProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolTaskProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolTaskProperties.getKeepAliveTime());
        executor.setThreadNamePrefix(threadPoolTaskProperties.getThreadNamePrefix());

        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }
}
